import uuid
from datetime import datetime
from typing import Any, Optional
from pydantic import BaseModel, Field

from enum import Enum


class TaskStatus(str, Enum):
    """任务状态枚举"""

    PENDING = "pending"  # 等待执行
    RUNNING = "running"  # 执行中
    COMPLETED = "completed"  # 已完成
    FAILED = "failed"  # 执行失败
    CANCELLED = "cancelled"  # 已取消
    RETRYING = "retrying"  # 重试中


class TaskType(str, Enum):
    """任务类型枚举"""

    LIGHT = "light"  # 轻度任务 - 异步处理
    HEAVY = "heavy"  # 重度任务 - 多进程处理
    SCHEDULED = "scheduled"  # 定时任务
    PERIODIC = "periodic"  # 周期性任务


class TaskPriority(int, Enum):
    """任务优先级"""

    LOW = 1
    MEDIUM = 2
    HIGH = 3
    CRITICAL = 4


class Task(BaseModel):
    """任务实体模型"""

    id: str = Field(default_factory=lambda: str(uuid.uuid4()))
    name: str = Field(..., description="任务名称")
    type: TaskType = Field(..., description="任务类型")
    func_name: str = Field(..., description="执行函数名")
    args: tuple[Any, ...] = Field(default=(), description="函数参数")
    kwargs: dict[str, Any] = Field(default_factory=dict, description="函数关键字参数")

    # 状态相关
    status: TaskStatus = Field(default=TaskStatus.PENDING, description="任务状态")
    priority: TaskPriority = Field(
        default=TaskPriority.MEDIUM, description="任务优先级"
    )

    # 执行结果
    result: Optional[Any] = Field(default=None, description="执行结果")
    error: Optional[str] = Field(default=None, description="错误信息")
    progress: float = Field(default=0.0, description="执行进度(0-100)")

    # 时间戳
    created_at: datetime = Field(default_factory=datetime.now, description="创建时间")
    started_at: Optional[datetime] = Field(default=None, description="开始执行时间")
    completed_at: Optional[datetime] = Field(default=None, description="完成时间")

    # 调度相关
    schedule_time: Optional[datetime] = Field(
        default=None, description="定时任务执行时间"
    )
    interval: Optional[int] = Field(default=None, description="周期性任务间隔(秒)")

    # 重试机制
    retry_count: int = Field(default=0, description="已重试次数")
    max_retries: int = Field(default=3, description="最大重试次数")

    # 执行配置
    timeout: Optional[int] = Field(default=None, description="超时时间(秒)")

    class Config:
        json_encoders = {datetime: lambda v: v.isoformat() if v else None}

    def to_response(self):
        """转换为TaskResponse对象"""
        from .task_request import TaskResponse

        return TaskResponse(
            id=self.id,
            name=self.name,
            type=self.type,
            status=self.status,
            priority=self.priority,
            created_at=self.created_at.isoformat(),
            started_at=self.started_at.isoformat() if self.started_at else None,
            completed_at=self.completed_at.isoformat() if self.completed_at else None,
            result=self.result,
            error=self.error,
            retry_count=self.retry_count,
        )
